package controller

import (
	"admin/model"
	"database/sql"
	"log"

	"github.com/gin-gonic/gin"
)

// 获取所有数量
func GetCounts(ctx *gin.Context) {
	var departments []model.Department
	var students []model.Student
	var classes []model.Classes
	db.Find(&departments)
	db.Find(&students)
	db.Find(&classes)
	ctx.JSON(200, gin.H{
		"code":       200,
		"classes":    len(classes),
		"student":    len(students),
		"department": len(departments),
	})
}

// 当type = 1 时，则使用系部查询学生数量
// 当type = 2 时，则使用班级查询学生数量
// 当type = 3 时，则使用系部查询班级数量
func GetCountFromType(ctx *gin.Context) {
	// 接受的数据
	type SelectField struct {
		Id   int `json:"id"`
		Type int `json:"type"`
	}
	type Count struct {
		Id sql.NullInt64
	}
	selectField := SelectField{}
	bindErr := ctx.ShouldBind(&selectField)
	if bindErr != nil {
		ctx.JSON(200, gin.H{
			"code":    400,
			"message": "数据格式错误",
		})
		return
	}
	var sql string = ""
	switch selectField.Type {
	case 1:
		sql = "select departments.id as departmentid, students.* from `departments` inner join `classes` on departmentid = classes.department_id left join students on classes.id = students.classes_id where departmentid = ?"
	case 2:
		sql = "select classes.id as classesid, students.* from `classes` left join `students` on classesid = students.classes_id  where classesid = ? "
	case 3:
		sql = "select departments.id as departmentid, classes.* from `departments` left join `classes` on departmentid = classes.department_id  where departmentid = ?"
	default:
		ctx.JSON(200, gin.H{
			"code":    400,
			"message": "不支持的类型",
		})
		return
	}
	// 关联表查到的数据
	var selector []Count
	count := db.Raw(sql, []int{
		selectField.Id,
	}).Scan(&selector).RowsAffected
	log.Println(selector, count)
}

func GetAllCountFormType(ctx *gin.Context) {
	// 接受的数据
	type SelectField struct {
		Type int `json:"type"`
	}
	type Count struct {
		Name  string `json:"name,omitempty"`
		Count int64  `json:"count,omitempty"`
	}
	selectField := SelectField{}
	bindErr := ctx.ShouldBind(&selectField)
	if bindErr != nil {
		ctx.JSON(200, gin.H{
			"code":    400,
			"message": "数据格式错误",
		})
		return
	}
	var sql string = ""
	switch selectField.Type {
	case 1:
		sql = "select departments.id as departmentid,departments.name as name,count(*) as count from `departments` inner join `classes` on departmentid = classes.department_id left join students on classes.id = students.classes_id group by departmentid"
	case 2:
		sql = "select classes.id as classesid,classes.name as name, count(*) as count from `classes` inner join `students` on classesid = students.classes_id group by classesid"
	default:
		ctx.AbortWithStatusJSON(200, gin.H{
			"code":    400,
			"message": "不支持的类型",
		})
	}
	// 关联表查到的数据
	var selector []Count
	db.Raw(sql).Scan(&selector)
	ctx.AbortWithStatusJSON(200, gin.H{
		"code":    200,
		"message": "获取成功",
		"data":    selector,
	})
}
